package com.xing.binbackend.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xing.binbackend.topology.model.CmdbConfig;
import com.xing.binbackend.topology.model.CmdbRelation;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class ReadFileUtils {
    private final ResourceLoader resourceLoader;

    public ReadFileUtils(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    private final ObjectMapper mapper = new ObjectMapper();

    /**
     * Java项目：类加载器方式
     */
    public String readJsonFile() {
        try (InputStream stream = ReadFileUtils.class.getResourceAsStream("topology.json")) {
            return mapper.readTree(stream).toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Spring项目：ResourceLoader加载方式
     */
    public String readJsonFileNew() {
        Resource resource = resourceLoader.getResource("topology.json");
        try (Reader stream = new InputStreamReader(resource.getInputStream(),
                StandardCharsets.UTF_8)) {
            return mapper.readTree(stream).toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public List<CmdbRelation> readCmdbRelations() {
        Resource resource = resourceLoader.getResource("cmdb_relation.json");
        try (Reader stream = new InputStreamReader(resource.getInputStream(),
                StandardCharsets.UTF_8)) {
            return mapper.convertValue(stream, new TypeReference<List<CmdbRelation>>() {
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public List<CmdbConfig> readCmdbConfigs() {
        Resource resource = resourceLoader.getResource("cmdb_config.json");
        try (Reader stream = new InputStreamReader(resource.getInputStream(),
                StandardCharsets.UTF_8)) {
            return mapper.convertValue(stream, new TypeReference<List<CmdbConfig>>() {
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
